######################################################################
# Time-stamp: <05/08/09 16:59:17 ostolop>
#
# Package: EP::Common::DBI::Folder
#
# DBI object mapping to the *folder* table
######################################################################
package EP::Common::DBI::Folder;

use strict;
use base qw ( EP::Common::DBI );

use EP::Config;

use EP::Common;
use EP::Common::Error qw ( :try );

use File::Path;

EP::Common::DBI::Folder->table ( 'ep_folder' );
EP::Common::DBI::Folder->sequence ( 'ep_folder_seq' );

EP::Common::DBI::Folder->columns ( Primary   => qw ( id ) );
EP::Common::DBI::Folder->columns ( Essential => qw ( name location parent owner ) );
EP::Common::DBI::Folder->columns ( Others    => qw ( group_write group_read other_read ) );

EP::Common::DBI::Folder->has_a ( owner  => 'EP::Common::DBI::User'   );
EP::Common::DBI::Folder->has_a ( parent => 'EP::Common::DBI::Folder' );

EP::Common::DBI::Folder->add_trigger ( after_delete => \&_after_delete );

# Sub: create
#   Overrides the default *create* method to make sure that the physical directory is created at the same time the db
#   entry is made.
sub create {
  my $self = shift;
  my ($params) = @_;

  my ( $folder ) = $self->do_transaction (
    sub {
      my $self = shift;
      my ($params) = @_;

      my $folder = $self->SUPER::create ( $params );
      $self->_create_physical_directory ( $params->{location} );

      return $folder;
    }, $self, $params );

  return $folder;
}

# Sub: _create_physical_directory
#   Creates the physical directory on the disk, as indicated by the *location* field.
sub _create_physical_directory {
  my $self = shift;
  my ($location) = @_;

  die "Need to pass a location to create directory!" if not $location;

  my $rc = mkdir "$EP::Config::h->{EPNG_USRDATA_PATH}/$location";

  if ( not $rc ) {
    warn "Failed to create directory ($!)" if DEBUG;
    throw EP::Common::Error ( -value => FS_CREATE_USER_DIR_FAILURE );
  }
}

# Sub: _after_delete
#   Special delete trigger to make sure the physical directory (and *EVERYTHING IN AND UNDER IT*) gets deleted when the
#   folder is removed from the database.
sub _after_delete {
  my $self = shift;

  die "Folder location not set! Can't delete!" if not $self->location;

  # send rmtree output to stderr if DEBUG. If DEBUG == 0, no output will be produced here.
  select (STDERR);
  rmtree "$EP::Config::h->{EPNG_USRDATA_PATH}/" . $self->location, DEBUG, 1;
  select (STDOUT);
}

1;
